<?php
class admin_model_user_manager extends model
{

    public function get_users($key = '', $status = -1, $order_by = 'ordering', $order_by_dir = 'ASC', $offset = 0, $limit = 20)
    {
        $query = 'SELECT * FROM `bone_user` WHERE 1 ';
        if ($key !== '') $query .= ' AND (`username` LIKE \'%' . $key . '%\' OR `name` LIKE \'%' . $key . '%\' OR `email` LIKE \'%' . $key . '%\')';
        if ($status != -1) $query .= ' AND `block`=' . $status;
        
        $query .= ' ORDER BY `' . $order_by . '` ' . $order_by_dir;
        
        $db = bone::get_db();
        return $db->get_objs($query, $offset, $limit);
    }

    public function get_user_sum($key = '', $status = -1)
    {
        $query = 'SELECT COUNT(*) FROM `bone_user` WHERE 1 ';
        if ($key !== '') $query .= ' AND (`username` LIKE \'%' . $key . '%\' OR `name` LIKE \'%' . $key . '%\' OR `email` LIKE \'%' . $key . '%\')';
        if ($status != -1) $query .= ' AND `block`=' . $status;
        $db = bone::get_db();
        return $db->get_result($query);
    }

    public function unblock($ids)
    {
        $db = bone::get_db();
        if (!$db->execute('UPDATE `bone_user` SET `block`=0 WHERE `id` IN(' . $ids . ')'))
        {
            $this->set_error($db->get_error());
            return false;
        }
        return true;
    }

    public function block($ids)
    {
        $array = explode(',', $ids);
        if (in_array(1, $array))
        {
            $this->set_error('默认管理员不能屏蔽');
            return false;
        }
        
        $my = bone::get_admin();
        if (in_array($my->id, $array))
        {
            $this->set_error('不能屏蔽自已');
            return false;
        }
        
        $db = bone::get_db();
        if (!$db->execute('UPDATE `bone_user` SET `block`=1 WHERE `id` IN(' . $ids . ')'))
        {
            $this->set_error($db->get_error());
            return false;
        }
        return true;
    }

    public function delete($ids)
    {
        $array = explode(',', $ids);
        if (in_array(1, $array))
        {
            $this->set_error('默认管理员不能删除');
            return false;
        }
        
        $my = bone::get_admin();
        if (in_array($my->id, $array))
        {
            $this->set_error('不能删除自已');
            return false;
        }
        
        foreach ($array as $id)
        {
            $user = bone::get_table('user', 'user');
            $user->load($id);
            $this->delete_avatar($user);
            $user->delete();
        }
        return true;
    }

    public function delete_avatar($user)
    {
        if ($user->avatar != 'apps/user/avatars/0.png')
        {
            $old_file = BONE_ROOT . DS . str_replace('/', DS, $user->avatar);
            if (file_exists($old_file)) unlink($old_file);
            
            $old_file = BONE_ROOT . DS . str_replace('/', DS, $user->avatar_l);
            if (file_exists($old_file)) unlink($old_file);
            
            $old_file = BONE_ROOT . DS . str_replace('/', DS, $user->avatar_s);
            if (file_exists($old_file)) unlink($old_file);
        }
    }

    public function init_avatar($user_id)
    {
        $user = bone::get_table('user', 'user');
        $avatar = $user->avatar;
        $avatar_l = $user->avatar_l;
        $avatar_s = $user->avatar_s;
        
        $user->load($user_id);
        $this->delete_avatar($user);
        
        $user->avatar = $avatar;
        $user->avatar_l = $avatar_l;
        $user->avatar_s = $avatar_s;
        
        if (!$user->save())
        {
            $this->set_error($user->get_error());
            return false;
        }
        
        return true;
    }

    public function set_admin($user_id, $status)
    {
        if ($user_id == 1)
        {
            $this->set_error('默认管理员禁止改动');
            return false;
        }
        $db = bone::get_db();
        if (!$db->execute('UPDATE `bone_user` SET `is_admin`=' . $status . ' WHERE `id`=' . $user_id))
        {
            $this->set_error($db->get_error());
            return false;
        }
        return true;
    }

    public function check_username($username)
    {
        $db = bone::get_db();
        return $db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `username`=\'' . $username . '\'') == 0;
    }

    public function check_email($email)
    {
        $db = bone::get_db();
        return $db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `email`=\'' . $email . '\'') == 0;
    }

    public function edit()
    {
        
        if (post('username', '') == '')
        {
            $this->set_error('用户名不能为空');
            return false;
        }
        
        if (post('email', '') == '')
        {
            $this->set_error('邮箱不能为空');
            return false;
        }
        
        $password = post('password', '');
        if ($password != post('password2', ''))
        {
            $this->set_error('两次输入的密码不一致');
            return false;
        }
        
        $id = post('id', 0, 'int');
        
        $user = bone::get_table('user', 'user');
        $is_new = ($id == 0);
        if (!$is_new) $user->load($id);
        $user->bind(post());
        
        if ($is_new && $password == '')
        {
            $this->set_error('请输入密码');
            return false;
        }
        
        $db = bone::get_db();
        
        if ($is_new)
        {
            if ($db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `username`=\'' . $user->username . '\''))
            {
                $this->set_error('已存在此用户名');
                return false;
            }
            
            if ($db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `email`=\'' . $user->email . '\''))
            {
                $this->set_error('已存在此邮箱');
                return false;
            }
        }
        else
        {
            if ($db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `id`!=' . $user->id . ' AND `username`=\'' . $user->username . '\''))
            {
                $this->set_error('已存在此用户名');
                return false;
            }
            
            if ($db->get_result('SELECT COUNT(*) FROM `bone_user` WHERE `id`!=' . $user->id . ' AND `email`=\'' . $user->email . '\''))
            {
                $this->set_error('已存在此邮箱');
                return false;
            }
        }
        
        if ($password != "")
            $user->password = md5($password . 'Mr Bone');
        else
            unset($user->password);
        
        if ($is_new)
        {
            $user->register_time = time();
            $user->last_visit_time = time();
        }
        else
        {
            unset($user->register_time);
            unset($user->last_visit_time);
        }
        
        if ($user->id == 1)
        {
            $user->is_admin = 1;
            $user->block = 0;
        }
        
        $user->save();
        
        $avatar = $_FILES['avatar'];
        if ($avatar['error'] == 0)
        {
            $lib_image = bone::get_lib('image');
            $lib_image->open($avatar['tmp_name']);
            if ($lib_image->is_image())
            {
                $this->delete_avatar($user);
                
                $file_name = $user->id . '_' . date('YmdHis');
                
                $lib_image->resize_to(96, 96);
                $lib_image->save_to(BONE_ROOT . DS . 'apps' . DS . 'user' . DS . 'avatars' . DS . $file_name . '_l.' . $lib_image->get_type());
                $user->avatar_l = 'apps/user/avatars/' . $file_name . '_l.' . $lib_image->get_type();
                
                $lib_image->resize_to(64, 64);
                $lib_image->save_to(BONE_ROOT . DS . 'apps' . DS . 'user' . DS . 'avatars' . DS . $file_name . '.' . $lib_image->get_type());
                $user->avatar = 'apps/user/avatars/' . $file_name . '.' . $lib_image->get_type();
                
                $lib_image->resize_to(32, 32);
                $lib_image->save_to(BONE_ROOT . DS . 'apps' . DS . 'user' . DS . 'avatars' . DS . $file_name . '_s.' . $lib_image->get_type());
                $user->avatar_s = 'apps/user/avatars/' . $file_name . '_s.' . $lib_image->get_type();
                
                $user->save();
            }
        }
        
        if ($is_new)
        {
            $config = bone::get_config('system');
            
            $subject = $config->site_name . ' 网站的管理员为您添加了一个账号';
            
            $body = '<div style="padding:3px;font-size:12px;">';
            $body .= '<div style="padding:3px 5px;background-color:#f90;color:#fff;">您在 ' . $config->site_name . ' 网站上的账号信息</div>';
            $body .= '<div style="padding:20px;color:#666;">' . $config->site_name . ' 网站的管理员为您添加了一个账号， 账号信息如下：</div>';
            $body .= '<ul>';
            $body .= '<li>用户名：' . $user->username . '</li>';
            $body .= '<li>密码：' . $password . '</li>';
            $body .= '<li>邮箱：' . $user->email . '</li>';
            $body .= '<li>名字：' . $user->name . '</li>';
            $body .= '</ul>	';
            $body .= '<div style="padding:20px;color:#666;">请牢记您的账号信息，点击这里访问  <a href="' . BONE_URL . '" target="_blank">' . $config->site_name . '</a></div>';
            $body .= '<div style="padding:3px;border-top:#ddd 1px solid;font-size:10px;color:#bbb;">本邮件由系统发送给 ' . $user->email . '，请勿直接回复。</div>';
            $body .= '</div>';
            
            $lib_mail = bone::get_lib('mail');
            $lib_mail->set_subject($subject);
            $lib_mail->set_body($body);
            $lib_mail->to($user->email);
            $lib_mail->send();
        }
        
        return $user->id;
    }

}
?>